package edu.ynu.se.xiecheng.achitectureclass.service;

import edu.ynu.se.xiecheng.achitectureclass.common.service.LogicService;
import edu.ynu.se.xiecheng.achitectureclass.dao.SoilPHDao;
import edu.ynu.se.xiecheng.achitectureclass.dto.DataDTO;
import edu.ynu.se.xiecheng.achitectureclass.entity.AirTemperature;
import edu.ynu.se.xiecheng.achitectureclass.entity.CarbonDioxide;
import edu.ynu.se.xiecheng.achitectureclass.entity.Device;
import edu.ynu.se.xiecheng.achitectureclass.entity.SoilPH;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Spliterator;

@Service
public class SoilPHService extends LogicService<SoilPHDao, SoilPH, Long> {
    public SoilPHService(@Autowired SoilPHDao dao) {super(dao);}

    @Transactional
    public void SaveData(String name, Double Data, Device device) {
        SoilPH  soilPH = new SoilPH();
        soilPH.setName(name);
        soilPH.setData(Data);
        soilPH.setDevice(device);
        dao.save(soilPH);
    }
    @Transactional
    public Double getLatestData() {
        List<SoilPH> soilPHS = dao.findAll(Sort.by(Sort.Direction.DESC, "id"));
        SoilPH latest = soilPHS.get(0);
        return latest.getData();
    }

    @Transactional
    public List<DataDTO> get7Data() {
        List<SoilPH> allSoilPHS = dao.findAll(Sort.by(Sort.Direction.DESC, "id"));
        List<DataDTO> dataDTOS = new ArrayList<>();
        List<SoilPH> soilPHs = new ArrayList<>(allSoilPHS.subList(0, Math.min(allSoilPHS.size(), 7)));
        for (SoilPH soilPH : soilPHs) {
            DataDTO dataDTO = new DataDTO();
            dataDTO.setData(soilPH.getData());
            dataDTO.setGetTime(soilPH.getCreateTime());
            dataDTOS.add(dataDTO);
        }
        return dataDTOS;
    }
}
